package zheezes.protocol.impl.gbw;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import zheezes.util.Errno;


public class FnRegister {
	private static final Map<Integer, FnDesc> map = new HashMap<Integer, FnDesc>();

	static {
		InputStream in = FnRegister.class.getResourceAsStream("afn.xml");
		SAXReader reader = new org.dom4j.io.SAXReader();
		Document doc = null;
		try {
			doc = reader.read(in);
		} catch (DocumentException e) {
			System.exit(Errno.EIO);
		}
		Element items = doc.getRootElement();
		byte afn;
		short fn;
		int down = 0;
		int up = 0;
		String description = null;

		Attribute attr = null;
		for (Object ae : items.elements("afn")) {
			Element afne = (Element) ae;

			attr = afne.attribute("id");
			afn = (byte) Integer.parseInt(attr.getValue(), 16);
			
			if ((attr = afne.attribute("down")) != null) {
				down = Integer.parseInt(attr.getValue());
			}

			if ((attr = afne.attribute("up")) != null) {
				up = Integer.parseInt(attr.getValue());
			}

			for (Object fe : afne.elements("fn")) {
				Element fne = (Element) fe;

				attr = fne.attribute("id");
				fn = (short) Integer.parseInt(attr.getValue());
				
				if ((attr = fne.attribute("down")) != null) {
					down = Integer.parseInt(attr.getValue());
				}

				if ((attr = fne.attribute("up")) != null) {
					up = Integer.parseInt(attr.getValue());
				}

				if ((attr = fne.attribute("description")) != null) {
					description = attr.getValue();
				}

				map.put(getId(afn, fn), new FnDesc(afn, fn, down, up, description));
			}
		}
		try {
			in.close();
		} catch (IOException e) {
		}
	}

	private static final int getId(byte afn, short fn) {
		return (afn << 16) + fn;
	}

	public static final FnDesc query(byte afn, short fn) {
		return map.get(getId(afn, fn));
	}

	public static void main(String[] args) {
		FnDesc desc = query((byte) 0x8C, (short) 1);
		System.out.printf("afn = %02X, fn = %d, down = %d, desc = %s", desc.getAfn(), desc.getFn(), desc.getDown(), desc.getDescription());
	}
}
